<template>
  <div ref="editor" class="rich-editor">

  </div>
</template>

<script lang="ts">
import { upload } from '@/services/courses'
import Vue from 'vue'
// https://www.wangeditor.com/doc/pages/01-%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8/01-%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8.html
import E from 'wangeditor'
export default Vue.extend({
  name: 'RichEditor',
  props: {
    value: { // 编辑器是双向的
      type: String,
      default: ''
    }
  },
  mounted () {
    this.initEditor()
  },
  methods: {
    initEditor () {
      const editor = new E(this.$refs.editor as any)
      editor.config.onchange = (val:any) => {
        this.$emit('input', val)
      }
      editor.config.customUploadImg = async function (resultFiles:any, insertImgFn:any) {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        const fd = new FormData()
        fd.append('file', resultFiles[0])
        const { data } = await upload(fd)
        // console.log(data)

        // 上传图片，返回结果，将图片插入到编辑器中
        insertImgFn(data.data.name)
      }

      editor.create()
      editor.txt.html(this.value)
    }
  }
})
</script>

<style lang="scss" scoped>

</style>
